package com.base.common.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.zip.CRC32;

import org.apache.commons.codec.digest.DigestUtils;

/**
 * @author jiaqiang.yan
 * @date 2011-7-15
 * @email jiaqiang.yan@qunar.com
 * @version $id$
 */
public class DigestUtil extends DigestUtils {

    public String crc32Hex(byte[] data) {
        CRC32 crc = new CRC32();
        crc.update(data);
        return Long.toHexString(crc.getValue());
    }

    public String crc32Hex(String str) {
        return crc32Hex(str.getBytes());
    }

    public String crc32Hex(InputStream in) throws IOException {
        CRC32 crc = new CRC32();
        byte[] buf = new byte[1024];
        int len = in.read(buf);
        while (len != -1) {
            crc.update(buf, 0, len);
            len = in.read(buf);
        }
        return Long.toHexString(crc.getValue());
    }

    public long crc32(byte[] data) {
        CRC32 crc = new CRC32();
        crc.update(data);
        return crc.getValue();
    }

    public long crc32(String str) {
        return crc32(str.getBytes());
    }

    public long crc32(InputStream in) throws IOException {
        CRC32 crc = new CRC32();
        byte[] buf = new byte[1024];
        int len = in.read(buf);
        while (len != -1) {
            crc.update(buf, 0, len);
            len = in.read(buf);
        }

        return crc.getValue();
    }
}
